import React from "react"
import {compose, lifecycle, withHandlers, withState} from "recompose"
import {del, get, postJSON, postParam, putJSON, putParam} from "server"
import {DEV, env, pageSetting} from "project-config"
import {rootPath} from "init"
import {HOST} from "../../../../shared/project-config"
import download from "libs/download"

const orderCompose = compose(
  withState('dataSource', '$dataSource', []),
  withState('loading', '$loading', false),
  withState('selectedRowKeys', '$selectedRowKeys', []),
  withState('pagination', '$pagination', Object.assign({}, pageSetting)),
  withState('page', '$page', {}),
  withState('filters', '$filters', {}),
  withState('searchKey', '$searchKey', ''),
  withHandlers({
    getPageData: ({$pagination, pagination, $loading, $dataSource, $selectedRowKeys}) => {
      return (param, pageSize, pageNum) => {
        $loading(true)
        get(`/order/myDownload/${pageSize || 10}/${pageNum || 1}`, param)
          .then(page => {
            $dataSource(page.pageData)
            $selectedRowKeys([])
            pagination.total = page.total
            pagination.pageSize = pageSize || 10
            pagination.current = pageNum || 1
            $pagination(Object.assign({}, pagination))
          }).finally(() => {
          $loading(false)
        })
      }
    },
  }),
  withHandlers({
    onFastSearch: ({$searchKey, getPageData}) => {
      return (key) => {
        $searchKey(key)
        getPageData({clothingCode: key})
      }
    }
  }),
  withHandlers({
    onPageChange: ({searchKey, getPageData, $filters, $page}) => {
      return (page, filters) => {
        const param = {clothingCode: searchKey || ''}

        if (filters && filters['status']) {
          $filters(filters)
          $page(page)
          param['statusList'] = filters['status']
        }
        getPageData(param, page.pageSize, page.current)
      }
    },
    toDownload: () => {
      return (row) => {
        download(`${HOST}/order/download?fileIds=${row['fileId']}`)
      }
    },
    batchDownload: ({selectedRowKeys}) => {
      return () => {
        download(`${HOST}/order/download?${selectedRowKeys.map(i => `fileIds=${i}`).join("&")}`)
      }
    },
    onView: ({history}) => {
      return (row) => {
        history.push(`/${rootPath}/library/buy/${row.clothingId}`)
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {getPageData} = this.props
      getPageData()
    }
  })
)

export default orderCompose